﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace WebSite.ViewModels.Fields
{
    public class TokenInputField : FieldBase
    {
        private readonly string m_ControllerName;
        private readonly string m_ActionName;
        private readonly Dictionary<Guid, string> m_Values;

        public TokenInputField(string caption, string name, string value, string controllerName, string actionName, Dictionary<Guid, string> values)
            : base(caption, name, value, true)
        {
            m_Values = values;
            m_ActionName = actionName;
            m_ControllerName = controllerName;
        }

        public override IHtmlString Render(HtmlHelper htmlHelper)
        {
            UrlHelper urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection);

            string prepopulate;
            if (m_Values == null || !m_Values.Any())
            {
                prepopulate = String.Empty;
            }
            else
            {
                string jsonValues = String.Join(",", m_Values.Select(x => "{id:\"" + x.Key + "\", name:\"" + x.Value + "\"}"));
                prepopulate = String.Format(", prePopulate: [{0}]", jsonValues);
            }

            string javascript = String.Format(@"
                <script type='text/javascript'> 
                    $(document).ready(function() {{
                        $('#{0}').tokenInput('{1}', {{
                            theme: 'facebook',
                            noResultsText: 'Nenhum resultado',
                            searchingText: 'Procurando...',
                            preventDuplicates: true,
                            hintText: ''
                            {2}
                        }});
                    }});
                </script>",
                Name,
                urlHelper.Action(m_ActionName, m_ControllerName),
                prepopulate);

            return htmlHelper.Raw(javascript + htmlHelper.TextBox(Name, String.Empty, new { id = Name }).ToHtmlString());
        }
    }
}